package com.controller;

import com.po.*;
import com.service.ActivityService;
import com.service.LeadService;
import com.service.SuggestService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private LeadService leadService;

    @Autowired
    private ActivityService activityService;



    @GetMapping("/apply")
    public String apply() {
        return "apply";
    }


    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/";
    }

    @GetMapping( "/lead/{location}")
    @ResponseBody
    public Msg leader(@Valid Lead lead,HttpSession session,@PathVariable String location,Model model){
        User user=((User) session.getAttribute("user"));
        if(user.getState()==9){
            return Msg.error();//您是管理员，无法参与
        }else if(user.getState()==5){
            return Msg.fail();//管理员审核中...
        }else if(user.getState()==0|user.getState()==2){
            user.setState(5);
            userService.saveUser(user);
            lead.setUser(user);
            lead.setLocation(location);
            lead.setState(5);
            leadService.saveLead(lead);
            return Msg.success();//申请成功，请等待管理员审核...
        }else
            return Msg.none();//您已是负责人
    }

    @GetMapping("/info")
    public String info(Model model,HttpSession session){
        User u= (User) session.getAttribute("user");
        User user=userService.findInfo(u.getId());
        System.out.println(user);
        model.addAttribute("users",user);
        return "/my_info";
    }

    @GetMapping("/update/{location}")
    @ResponseBody
    public Msg update(@PathVariable String location,@RequestParam String name,@RequestParam int age,HttpSession session){
        User u= (User) session.getAttribute("user");
        User user=userService.findInfo(u.getId());
        user.setName(name);
        user.setAge(age);
        if(user.getLocation()==null) {
            user.setLocation(location);
        }
        userService.saveUser(user);
        return Msg.success();
    }

    @GetMapping("/activity")
    public String activity(HttpSession session,Model model){
        User u= (User) session.getAttribute("user");
        List<Activity> list=activityService.findActivity(u.getId());
        model.addAttribute("my_activity",list);
        return "/my_activity";
    }

}